<template>
	<view class="content">
		<map id="map" :longitude="longitude" :latitude="latitude" scale="14" controls="controls" @controltap="controltap"
			@tap="bindtapMap" :markers="markers" :polyline="polyline" @markertap="removeMarker" @labeltap="removeMarker"
			:polygons="polygons.length > 0 ? polygons : ''" style="width: 100%; height: 90vh;">
		</map>
		<button type="primary" @tap="toOther">修改围栏</button>
		<u-popup :show="showalert" mode="center" @close="closealert" @open="openalert">
			<view class="alert">
				<view>逃跑羊数:{{ errnum }}/{{ total }}</view>
				<scroll-view scroll-y="true" class="scroll-Y">
					<view class="scroll-view-item" v-for="item in errlist" :key="item._id">
						<view class="info">
							<image src="../../static/yang.jpg" mode=""></image>
							<view class="">
								<text>{{ item.id }}号</text>
								<text>{{ item.dikm }}km</text>
							</view>
						</view>
					</view>
				</scroll-view>
				<u-button type="primary" @tap="closes">关闭警告</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import QQMapWX from '../../common/qqmap-wx-jssdk.js'
import request from '../../utils/request'
export default {
	data() {
		return {
			latitude: 43.63, // 纬度  竖的是纬度
			longitude: 87.493, // 经度 横的是经度
			polyline: [], // 路线
			//围栏顶点坐标
			markers: [],
			//marke是定位的点
			polygons: [], // 多边形
			paramspolygones: [],
			qqmapsdk: null,
			music: null,
			showalert: false,
			errlist: [],
			total: 0,
			errnum: 0
		}
	},
	onLoad() {
		request('/cyp', null, 'GET')
			.then(({ data }) => {
				let array = data.data[0].fence;
				this.Inquire(array);
				this.polygons = [
					{
						points: [...array],
						fillColor: "#1791fc66", // 填充颜色
						strokeColor: "#FFF", // 描边颜色
						strokeWidth: 2, // 描边宽度
						zIndex: 3 // 层级
					}
				];
			})
			.catch(error => {
				// Handle error here
				console.error(error);
			});
			this.qqmapsdk = new QQMapWX({
				key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
			})
		//,
	},
	onUnload: function () {
		this.closealert()
		this.showalert = false
	},


	methods: {
		//创建标记点
		bindtapMap(e) {
			let tapPoint = {
				latitude: e.detail.latitude,
				longitude: e.detail.longitude
			}; // 获取点击的坐标
			// 向点的数组和围栏数组添加这个点
			this.markers.push(tapPoint)
			this.polygonsMarkers.push(tapPoint)
			let markers = this.markers
			let newContent = markers.length
			let markerItem = {
				callout: { //配置气泡，配置气泡后，title会失效
					content: newContent++, //'气泡内容'
					padding: 5, //文本边缘留白，文字和边界宽度
					borderRadius: 2,
					bgColor: '#ffffff', // 背景颜色
					display: 'ALWAYS', // 显示方式，可以配置点击或一直显示，BYCLICK点击显示
					anchorY: -15,
					anchorX: 15,
					zIndex: 2
				},
				id: newContent,
				latitude: null,
				longitude: null,
				iconPath: '../../static/Markers.png',
				width: '34px',
				height: '34px',
				rotate: 0,
				alpha: 1,
				zIndex: 3
			}
			markerItem.latitude = tapPoint.latitude;
			markerItem.longitude = tapPoint.longitude;
			markers.push(markerItem)
			// console.log("markerItem",markers);
			this.markers = markers
			this.polygonsMarkers.push(markerItem)
		},

		// 生成围栏
		creatPolygons() {
			//创建多边形围栏/服务范围
			console.log("我要创建围栏", this.polygonsMarkers);
			if (this.polygonsMarkers.length < 3) {
				return uni.showToast({
					title: '请先在地图上标记点,且不少于三个点',
					icon: 'none'
				})
			}
			let polygons = [...this.polygonsMarkers];
			let newArray = [];
			for (let j = 0; j < markers.length; j++) {
				let obj = {
					latitude: markers[j].latitude,
					longitude: markers[j].longitude,
				};
				newArray.push(obj);
				console.log("newArray", newArray);
			}
			//polygons是围栏的点
			this.polygons = [{
				points: polygons,
				fillColor: "#1791fc66", // 填充颜色
				strokeColor: "#FFF", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 3 //层级
			}]
		},

		toOther() {
			this.close()
			uni.navigateTo({
				url: '/pages/content/content'
			})
		},
		Inquire(array) {
			request('/gjs/Inquire', { markers: array }, 'POST')
				.then(({ data }) => {
					let { list, errornum, total } = data;
					this.errnum = errornum;
					this.total = total;
					this.markers = list;
					list.forEach(item => {
						this.getPathing(item);
					});
					if (list.length !== 0) {
						this.ScanAudio();
						this.openalert();
					}
				})
				.catch(error => {
					// Handle error here
					console.error(error);
				});

		},
		ScanAudio() {
			var music = null;
			music = uni.createInnerAudioContext()
			music.loop = true
			music.src =
				'https://img.tukuppt.com/newpreview_music/09/00/13/5c8902563671136874.mp3';
			music.play()
			this.musics = music
			uni.vibrateLong()
			this.thime = setInterval(() => {
				uni.vibrateLong()
			}, 1000)
		},
		closealert() {
			this.showalert = false
			this.musics.destroy()
			clearInterval(this.thime)
		},
		closes() {
			this.musics.destroy()
			clearInterval(this.thime)
		},
		openalert() {
			this.showalert = true
		},
		seek() {
			this.close()
			this.showalert = false
			uni.navigateTo({
				url: '/pages/index/index'
			})
		},
		getPathing(obj) {
			// 暂存this---direction方法里面会用到
			const that = this
			// 获取当前地理位置
			this.qqmapsdk.direction({
				mode: 'driving',
				from: {
					latitude: 43.61122246320031,
					longitude: 87.50078201293945
				},
				to: {
					latitude: obj.latitude,
					longitude: obj.longitude
				},
				// 执行成功的回调
				success: function (res, data) {
					// //坐标解压（返回的点串坐标，通过前向差分进行压缩）
					let dikm = Number(res.result.routes[0].distance) / 1000
					// console.log(dikm.toFixed(2),111);
					that.errlist.push({
						id: obj.id,
						_id: obj._id,
						dikm: dikm.toFixed(2)
					})
					console.log(that.errlist);
				}
			})
		}
	}
}
</script>

<style lang="scss">
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.alert {
	width: 600rpx;
	height: 500rpx;
}

.scroll-Y {
	width: 600rpx;
	height: 460rpx;
}

.scroll-view-item {
	height: 200rpx;
	font-size: 36rpx;

	.info {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: space-between;
		line-height: 120rpx;

		image {
			width: 130rpx;
			height: 130rpx;
			border-radius: 50%;
		}
	}
}


/* button {
	width: 100%;
} */
</style>